<template>
  <div class="personal-view">
    <div class="left">
      <div class="top">
        <img :src="PersonalData.imgUrl" alt="" draggable="false" />
        <div class="info">
          <div class="username">{{ PersonalData.username }}</div>
          <div class="intro">{{ PersonalData.intro }}</div>
          <div class="tag-btn">
            <div class="tags">
              <el-tag
                v-for="(item, index) in PersonalData.userTags"
                :key="index"
                >{{ item }}</el-tag
              >
            </div>
            <div class="btn">
              <el-button
                @click="$router.push('/personal/setting')"
                v-if="userId === personalId"
                type="primary"
                >设置</el-button
              >
              <el-button
                v-else
                @click="followUser"
                :type="isFollow ? '' : 'primary'"
                >{{ isFollow ? "已关注" : "关注" }}</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div class="bottom">
        <el-tabs v-model="activeName" @tab-click="selectPostCategory">
          <el-tab-pane label="发表" name="first">
            <el-empty
              v-if="postData.length === 0 && !loading"
              description="暂无数据"
            ></el-empty>
            <post-view
              v-for="(item, index) in postData"
              :key="index"
              :postItem="item"
              :activeName="activeName"
              @deletePost="deletePost"
            ></post-view>
            <div v-if="loading" class="loading">加载中...</div>
          </el-tab-pane>
          <el-tab-pane label="收藏" name="second">
            <div
              class="collect-category"
              v-for="(item, index) in collectData"
              :key="index"
            >
              <div class="collect-title">{{ item.categoryName }}</div>
              <div class="collect-info">
                <span>更新于 {{ item.updateTime.split("T")[0] }}</span>
                <span>|</span>
                <span>{{ item.count }} 内容</span>
                <span>|</span>
                <span>{{ item.isPrivate ? "私密" : "公开" }}</span>
                <span>|</span>
                <div
                  class="btn"
                  @click="
                    selectOpenCollect =
                      selectOpenCollect === null ? index : null
                  "
                >
                  <span>{{
                    index !== selectOpenCollect ? "展开" : "收起"
                  }}</span>
                  <svg-icon
                    :icon-file-name="
                      index !== selectOpenCollect ? 'down' : 'up'
                    "
                  ></svg-icon>
                </div>
                <el-dropdown trigger="click">
                  <i class="el-icon-more"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      @click.native="editCollect(item)"
                      :disabled="item.categoryName === '默认收藏夹'"
                      icon="el-icon-edit"
                      >编辑</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="deleteCollect(item)"
                      :disabled="item.categoryName === '默认收藏夹'"
                      icon="el-icon-delete"
                      >删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="collect-content" v-if="index === selectOpenCollect">
                <span
                  v-for="i in item.contentData"
                  :key="i.postId"
                  @click="goToLookPost(i)"
                  >{{ i.title }}</span
                >
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="点赞" name="third">
            <el-empty
              v-if="postData.length === 0 && !loading"
              description="暂无数据"
            ></el-empty>
            <post-view
              v-for="(item, index) in postData"
              :key="index"
              :postItem="item"
              :activeName="activeName"
            ></post-view>
            <div v-if="loading" class="loading">加载中...</div>
          </el-tab-pane>
          <el-tab-pane label="关注" name="fourth">
            <follow-view
              @removeFollow="removeFollow"
              @addFollow="addFollow"
              :loginFollowList="loginFollowList"
              :personalId="personalId"
            ></follow-view>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="right">
      <div class="top">
        <div class="title">个人成就</div>
        <div class="content">
          <div class="item">
            <div class="icon">
              <svg-icon icon-file-name="like-fill"></svg-icon>
            </div>
            <span>文章被点赞 {{ PersonalData.likesCount }}</span>
          </div>
          <div class="item">
            <div class="icon">
              <svg-icon icon-file-name="eye-fill"></svg-icon>
            </div>
            <span>文章被浏览 {{ PersonalData.postPageViews }}</span>
          </div>
        </div>
      </div>
      <div class="follow-info">
        <div>
          <span>关注</span>
          <span>{{ PersonalData.followingCount }}</span>
        </div>
        <div class="line"></div>
        <div>
          <span>粉丝</span>
          <span>{{ PersonalData.followersCount }}</span>
        </div>
      </div>
      <div class="time">
        <span>加入于</span>
        <span>{{ formatDate(PersonalData.createTime) }}</span>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      top="20vh"
      :append-to-body="true"
      width="30%"
    >
      <div class="dialog-top">
        <span>编辑收藏夹</span>
        <svg-icon
          icon-file-name="close"
          @click="dialogVisible = false"
        ></svg-icon>
      </div>
      <div class="add-collect">
        <el-input
          type="text"
          placeholder="输入收藏夹标题"
          v-model="categoryForm.categoryName"
          maxlength="10"
          show-word-limit
        >
        </el-input>
        <div class="isPrivate" style="padding: 10px">
          <span style="float: left">私密</span>
          <el-switch style="float: right" v-model="categoryForm.isPrivate">
          </el-switch>
        </div>
        <div style="position: absolute; bottom: 20px; right: 20px">
          <el-button type="primary" @click="updateCategory">确认修改</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import PostView from "./components/PostView.vue";
import FollowView from "./components/FollowView.vue";
import { getUserId } from "../../utils/auth";
import {
  getPersonalInfo,
  getLoginUserFollow,
  getPersonalPost,
  deletePost,
  getCollectData,
  deleteCollect,
  updateCategory,
} from "../../api/personal";
import { cancelFollow, Follow } from "../../api/post";
export default {
  components: {
    PostView,
    FollowView,
  },
  data() {
    return {
      // 当前这个页面显示的信息是哪个用户的
      personalId: "",
      personalName: "",
      // 当前登陆用户的id
      userId: getUserId(),
      activeName: "first",
      // 顶部卡片的数据
      PersonalData: {},
      // 当前登陆用户关注用户id列表
      loginFollowList: [],
      // 渲染的文章id，这里分为发布、点赞、收藏三类
      postData: [],
      currentPage: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      // 是否关注
      isFollow: false,
      /* 收藏夹相关 */
      isOpenCollect: false, // 是否展开收藏夹
      collectData: [], // 用户拥有的收藏夹数据
      selectOpenCollect: null, // 展开的收藏夹的 index
      /**
       * 编辑收藏夹相关
       */
      categoryForm: {
        userId: "",
        categoryId: "",
        categoryName: "",
        isPrivate: false,
      },
      dialogVisible: false,
    };
  },
  methods: {
    // 关注用户
    followUser() {
      if (this.isFollow) {
        // 已经关注则发送取消关注请求
        cancelFollow(this.userId, this.personalId).then((res) => {
          if (res.data.code === 1) {
            this.$notify({
              title: "成功",
              message: "取消关注成功",
              type: "success",
            });
            this.isFollow = false;
          } else {
            this.$message.error("网络错误");
          }
        });
      } else {
        // 未关注则发送关注请求
        Follow(this.userId, this.personalId).then((res) => {
          if (res.data.code === 1) {
            this.$notify({
              title: "成功",
              message: "关注成功",
              type: "success",
            });
            this.isFollow = true;
          } else {
            this.$message.error("网络错误");
          }
        });
      }
    },
    // 删除文章
    deletePost(postId) {
      this.$confirm("此操作将永久删除该文章, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户确认删除操作
          deletePost(postId).then((res) => {
            if (res.data.code === 1) {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
              this.selectPostCategory();
            } else {
              this.$notify.error({
                title: "错误",
                message: "网络错误",
              });
            }
          });
        })
        .catch(() => {
          this.$notify.info({
            title: "消息",
            message: "已取消删除",
          });
        });
    },
    // 选中的文章类别
    selectPostCategory() {
      if (this.activeName === "fourth") {
        return;
      }
      this.postData = [];
      this.currentPage = 1;
      this.hasMore = true;
      this.getPostData();
    },
    ...mapMutations({
      changeBottom: "scrollBar/changeBottom",
    }),
    loadMore() {
      if (this.loading || this.activeName === "second") return;
      this.getPostData();
      // 重新加载数据结束后，将滚动条是否置地变量置位false
      this.changeBottom();
    },
    // 获取展示的文章数据
    getPostData() {
      if (this.activeName === "second") {
        this.getCollectData();
        return;
      }
      if (!this.hasMore) {
        return;
      }
      this.loading = true;
      getPersonalPost(
        this.activeName,
        this.personalId,
        this.currentPage,
        this.pageSize
      ).then((res) => {
        if (res.data.code === 1) {
          this.postData = [...this.postData, ...res.data.data.rows];
          this.currentPage++;
          if (this.postData.length === res.data.data.total) {
            this.hasMore = false;
          }
          this.loading = false;
        } else {
          this.$message.error("网络错误");
        }
      });
    },
    // 获取收藏数据
    getCollectData() {
      getCollectData(getUserId()).then((res) => {
        if (res.data.code === 1) {
          this.collectData = res.data.data;
        } else {
          this.$message.error("网络错误");
        }
      });
    },
    // 删除收藏夹
    deleteCollect(val) {
      deleteCollect(val.categoryId).then((res) => {
        if (res.data.code === 1) {
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
          });
          this.getCollectData();
          this.selectOpenCollect = null;
        } else {
          this.$message.error("网络错误");
        }
      });
    },
    // 编辑收藏夹
    editCollect(val) {
      this.categoryForm.userId = val.userId;
      this.categoryForm.categoryId = val.categoryId;
      this.categoryForm.categoryName = val.categoryName;
      this.categoryForm.isPrivate = val.isPrivate;
      this.dialogVisible = true;
    },
    updateCategory() {
      updateCategory(this.categoryForm).then((res) => {
        if (res.data.code === 1) {
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.getCollectData();
        } else {
          this.$message.error("网络错误");
        }
      });
    },
    // 从收藏跳转到文章浏览页面
    goToLookPost(item) {
      // 使用Vue Router获取目标路由的完整URL
      const routePath = this.$router.resolve({
        name: "LookPost",
        params: {
          postId: item.postId,
          postTitle: item.title,
        },
      }).href;
      window.open(routePath, "_blank");
    },
    // 处理日期
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    // 获取最上面的个人信息卡片数据
    getPersonalInfo() {
      getPersonalInfo(this.personalId).then((res) => {
        if (res.data.code === 1) {
          this.PersonalData = res.data.data;
          // console.log(this.PersonalData);
        } else {
          this.$message.error("网络错误");
        }
      });
    },
    // 获取登陆用户关注用户列表
    getLoginUserFollow() {
      getLoginUserFollow(getUserId()).then((res) => {
        if (res.data.code === 1) {
          this.loginFollowList = res.data.data;
          this.isFollow = this.loginFollowList.includes(
            parseInt(this.personalId)
          );
        } else {
          this.$message.error("网络错误");
        }
      });
    },
    // 在关注列表中删除取消关注的用户id
    removeFollow(followId) {
      this.loginFollowList = this.loginFollowList.filter(
        (item) => item !== followId
      );
    },
    // 在关注列表中增加取消关注的用户id
    addFollow(followId) {
      this.loginFollowList.push(followId);
    },
    // 更新标题
    updateTitle() {
      document.title = `个人主页 - ${this.personalName}`; // 使用传递的用户名更新标题
    },
  },
  mounted() {
    this.getPersonalInfo();
    this.getLoginUserFollow();
    this.getPostData();
    this.updateTitle();
  },
  created() {
    this.personalId = this.$route.params.personalId;
    this.personalName = this.$route.params.personalName;
  },
  computed: {
    // vuex中滚动条状态变量
    ...mapState({
      isBottom: (state) => state.scrollBar.isBottom,
    }),
  },
  watch: {
    // 监听滚动条，当为true，也就是触底执行loadMore()
    isBottom(newVal) {
      if (newVal) {
        this.loadMore(); // 当 isBottom 变为 true 时触发获取数据的函数
      }
    },
    personalName() {
      this.updateTitle(); // 如果用户名更新了，重新设置标题
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../assets/ElementUIStyle/el-button.css");
.personal-view {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
  gap: 24px;
  .left {
    margin-left: 16%;
    display: flex;
    flex-direction: column;
    width: 50%;
    .top {
      padding: 20px 30px;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      gap: 20px;
      background-color: #fff;
      border-radius: 3px;
      img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        user-select: none;
      }
      .info {
        width: 100%;
        display: flex;
        flex-direction: column;
        line-height: 25px;
        gap: 20px;
        .username {
          font-size: 24px;
          font-weight: 800;
        }
        .intro {
          width: 80%;
        }
        .tag-btn {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .tags {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            gap: 15px;
          }
        }
      }
    }
    .bottom {
      min-height: 440px;
      margin-top: 20px;
      background-color: #fff;
      border-radius: 3px;
      .loading {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 10px;
        color: #ccc;
      }
      .collect-category {
        display: flex;
        flex-direction: column;
        padding: 10px;
        gap: 20px;
        border-bottom: 1px solid #f2f3f5;
        .collect-title {
          font-size: 18px;
          font-weight: 800;
        }
        .collect-info {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #555666;
          font-size: 12px;
          gap: 10px;
          .btn {
            display: flex;
            align-items: center;
            cursor: pointer;
            gap: 5px;
            svg {
              width: 15px;
              height: 15px;
            }
          }
          .el-dropdown {
            position: absolute;
            right: 20px;
            cursor: pointer;
          }
        }
        .collect-content {
          display: flex;
          flex-direction: column;
          gap: 10px;
          background-color: rgba(245, 246, 247, 0.8);
          padding: 10px;
          span {
            cursor: pointer;
            color: #555666;
            font-size: 16px;
            &:hover {
              color: #409eff;
            }
            padding-bottom: 5px;
            border-bottom: 1px solid #f2f3f5;
          }
        }
      }
    }
  }
  .right {
    display: flex;
    flex-direction: column;
    gap: 20px;
    width: 18%;
    .top {
      background-color: #fff;
      border-radius: 3px;
      .title {
        padding: 15px 20px 15px 20px;
        font-size: 18px;
        font-weight: 600;
        border-bottom: 1px solid #f2f3f5;
      }
      .content {
        padding: 10px 20px;
        display: flex;
        flex-direction: column;
        gap: 10px;
        .item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .icon {
            border-radius: 50%;
            width: 30px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #e1efff;
            color: #7bb9ff;
            svg {
              width: 18px;
              height: 18px;
            }
          }
          span {
            font-size: 14px;
          }
        }
      }
    }
    .follow-info {
      background-color: #fff;
      padding: 10px 20px;
      display: flex;
      justify-content: space-evenly;
      .line {
        height: 100%;
        width: 1px;
        background-color: #f2f3f5;
      }
      div {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
        // 第一个span
        span:nth-child(1) {
          font-size: 16px;
          color: #31445b;
        }
        // 第二个span
        span:nth-child(2) {
          font-size: 14px;
          font-weight: 600;
          color: #31445b;
        }
      }
    }
    .time {
      border-top: 1px solid #e0e1eb;
      border-bottom: 1px solid #e0e1eb;
      display: flex;
      justify-content: space-between;
      padding: 20px 10px;
    }
  }
}
</style>

<style scoped>
::v-deep .el-tabs__nav {
  margin-left: 20px !important;
}
::v-deep .el-tabs__content {
  padding: 0 15px 15px 15px !important;
}
::v-deep .el-tabs__item {
  color: #909090 !important;
}
::v-deep .el-tabs__item.is-active {
  color: #252933 !important;
}
.el-tag {
  border-radius: 0 !important;
  height: 25px;
  line-height: 25px;
}
</style>

<style scoped>
::v-deep .el-dialog__header {
  display: none !important;
}

::v-deep .el-dialog__body {
  padding-top: 10px;
  height: 424px;
}

::v-deep .el-dialog__body > .dialog-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
}

::v-deep .el-dialog__body > .dialog-top > span {
  font-size: 18px !important;
  font-weight: 600 !important;
}

::v-deep .el-dialog__body > .dialog-top > svg {
  color: #8a919f;
  cursor: pointer;
}
</style>